雖然鐵人賽比完了,但是我依然會把這個專案繼續寫下去,如果還沒看之前Angular Stock的朋友,
麻煩幫我點連結進去看。
好,接下來我們遇到一個問題在於說,不管有沒有登入的人,都可以進入我們的主頁(index.html)
因此我們需要利用Route Guards來阻擋未符合驗證規則的人進入頁面
那什麼是Route Guards呢?
At the moment, any user can navigate anywhere in the application any time, but sometimes you need to control access to different parts of your application for various reasons, some of which might include the following:
簡單來說就是我們有些頁面不想讓沒有經過身分驗證的使用者使用,又或是
我們想要使用者確認是否要捨棄目前頁面上輸入的資料
因此我們會設下一些限制
A guard's return value controls the router's behavior:
true
, the navigation process continues.false
, the navigation process stops and the user stays put.[UrlTree](https://angular.io/api/router/UrlTree)
, the current navigation cancels and a new navigation is initiated to the [UrlTree](https://angular.io/api/router/UrlTree)
returned.在此次我們會針對navigation process進行修改
首先我們先在service裡新增auth.service
ng g s /service/auth
接著新增一個shares資料夾,並且在裡面新增auth.guard
ng g guard /shares/auth
然後實作auth.service
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor() {}
//檢查sessionStorage的token有沒有值
checkIsLogin(): boolean {
const token = sessionStorage.getItem('token') || '';
if ( token ){
return true;
}
return false;
}
}
然後在auth.guard使用
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../service/auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private rooter: Router){
}
//CanActivate 所需要實作的方法
canActivate(): boolean{
if (this.authService.checkIsLogin()){
return true;
}
//無法通過驗證的請求轉到loginComponent
this.rooter.navigate(['login']);
return false;
}
}
在appModule上面修改設定加上
const routes: Routes = [
{ path: '', component: LoginComponent },
{ path: 'login', component: LoginComponent },
{ path: 'index', component: IndexComponent, canActivate: [AuthGuard] },
{ path: 'exchange/getStockDayAll', component: DailyTranctionStockComponent, canActivate: [AuthGuard] },
{ path: '**', component: ErrorComponent }, // 萬用路由,不可設在前面
];
接著直接在網址輸入http://localhost:4200/main 就會發現被轉導到登入頁了喔